package sz.szsmk.citizencard.ui.base;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;
import com.trello.rxlifecycle.LifecycleTransformer;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import javax.inject.Inject;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.dialog.CustomProgressDialog;
import sz.szsmk.citizencard.dialog.NetRequestTipsDialog;
import sz.szsmk.citizencard.ioc.Compontent.AppCompontent;
import sz.szsmk.citizencard.util.PermissionsUtils;


/**
 * 涉及dagger业务逻辑继承此类。如果没有业务逻辑，或只是作为容器，继承普通的AppCompatActivity
 *
 * @author sinner
 * @time 2017/3/20 下午2:57
 * @mail wangzhongfu@xwtec.cn
 */

public abstract class IBaseStatusBarActivity<T extends IBaseContact.IBasePresenter, V extends ViewDataBinding> extends RxAppCompatActivity implements IBaseContact.IBaseView {

    LinearLayout mRootBaseView;//根布局
    View titleView;//include的titleBar

    View mStateLayout;//include的state_layout
    LinearLayout ll_page_state_error;//stateLayout网络错误的布局
    LinearLayout ll_page_state_empty;//stateLayout无数据的布局
    Button btReload;//网络错误重新加载的布局


    private final int mRequestCode = 1024;
    private RequestPermissionCallBack mRequestPermissionCallBack;
    /**
     * 把 Presenter 提取到基类需要配合基类的 initInjector() 进行注入，如果继承这个基类则必定要提供一个 Presenter 注入方法，
     * 该APP所有 Presenter 都是在 Module 提供注入实现，也可以选择提供另外不带 Presenter 的基类
     */
    @Inject
    protected T mPresenter;
    private CustomProgressDialog progressDialog;

    /**
     * 绑定布局文件
     *
     * @return 布局文件ID
     */
    @LayoutRes
    protected abstract int attachLayoutRes();

    /**
     * Dagger 注入
     */
    protected abstract void initInjector();

    /**
     * 初始化视图控件
     */
    protected abstract void initViews();

    /**
     * 更新视图控件
     */
    protected abstract void updateViews();

    protected V dataBinding;


    private NetRequestTipsDialog mNetRequestTipsDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initSystemBar();
        setContentView(R.layout.base_activity);

        dataBinding = DataBindingUtil.setContentView(this, attachLayoutRes());
        initInjector();
        if (mPresenter != null) {
            mPresenter.attachView(this);
        }
        /*设置为竖屏*/
        initViews();
        updateViews();

//        mRootBaseView = (LinearLayout) findViewById(R.id.activity_base_root);
//
//        mStateLayout = findViewById(R.id.activity_base_state_layout);
//        btReload = (Button) findViewById(R.id.state_layout_error_bt);
    }


//    @Override
//    public void setContentView(int layoutResID) {
//
//        View view = getLayoutInflater().inflate(layoutResID, null);
//        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
//
//        if (null != mRootBaseView) {
//            mRootBaseView.addView(view, lp);
//        }
//    }

//    public void changePageState(PageState pageState) {
//        switch (pageState) {
//            case NORMAL:
//                if (mStateLayout.getVisibility() == View.VISIBLE) {
//                    mStateLayout.setVisibility(View.GONE);
//                }
//                break;
//            case ERROR:
//                if (mStateLayout.getVisibility() == View.GONE) {
//                    mStateLayout.setVisibility(View.VISIBLE);
//                    ll_page_state_error.setVisibility(View.VISIBLE);
//                    btReload.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View view) {
////                            reloadInterface.reloadClickListener();
//                        }
//                    });
//                    ll_page_state_empty.setVisibility(View.GONE);
//                }
//                break;
//            case EMPTY:
//                if (mStateLayout.getVisibility() == View.GONE) {
//                    mStateLayout.setVisibility(View.VISIBLE);
//                    ll_page_state_error.setVisibility(View.GONE);
//                    ll_page_state_empty.setVisibility(View.VISIBLE);
//                }
//                break;
//        }
//
//    }

//    public enum PageState {
//        /**
//         * 数据内容显示正常
//         */
//        NORMAL,
//        /**
//         * 数据为空
//         */
//        EMPTY,
//        /**
//         * 数据加载失败
//         */
//        ERROR
//    }

    protected void initSystemBar() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarDarkFont(false, 0f)
                .statusBarColor(R.color.color_2184FA).init();
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.<T>bindToLifecycle();
    }


    /**
     * 获取 ActivityModule
     *
     * @return ActivityModule
     */
//    protected ActivityModule getActivityModule() {
//        return new ActivityModule(this);
//    }


    /**
     * 添加 Fragment
     *
     * @param containerViewId
     * @param fragment
     */
    protected void addFragment(int containerViewId, Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(containerViewId, fragment);
        fragmentTransaction.commit();
    }

    /**
     * 添加 Fragment
     *
     * @param containerViewId
     * @param fragment
     */
    protected void addFragment(int containerViewId, Fragment fragment, String tag) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        // 设置tag，不然下面 findFragmentByTag(tag)找不到
        fragmentTransaction.add(containerViewId, fragment, tag);
        fragmentTransaction.addToBackStack(tag);
        fragmentTransaction.commit();
    }

    /**
     * 替换 Fragment
     *
     * @param containerViewId
     * @param fragment
     */
    protected void replaceFragment(int containerViewId, Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(containerViewId, fragment);
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    protected void showLoadingDialog() {
        if (null == mNetRequestTipsDialog) {
            mNetRequestTipsDialog = new NetRequestTipsDialog();
//            progressDialog = new CustomProgressDialog(this);
//            progressDialog.show();
        }

        android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(mNetRequestTipsDialog, this.getClass().getSimpleName());
        ft.commitAllowingStateLoss();
    }

    protected void dismissLoadingDialog() {
        if (null != mNetRequestTipsDialog) {
            mNetRequestTipsDialog.dismissAllowingStateLoss();
            mNetRequestTipsDialog = null;
        }
//        if (null != progressDialog) {
//            progressDialog.dismiss();
//            progressDialog = null;
//        }
    }

    /**
     * 替换 Fragment
     *
     * @param containerViewId
     * @param fragment
     */
    protected void replaceFragment(int containerViewId, Fragment fragment, String tag) {
        if (getSupportFragmentManager().findFragmentByTag(tag) == null) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            // 设置tag
            fragmentTransaction.replace(containerViewId, fragment, tag);
            fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            // 这里要设置tag，上面也要设置tag
            fragmentTransaction.addToBackStack(tag);
            fragmentTransaction.commit();
        } else {
            // 存在则弹出在它上面的所有fragment，并显示对应fragment
            getSupportFragmentManager().popBackStack(tag, 0);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mPresenter != null) {
            mPresenter.detachView();
        }
    }

    /**
     * 获取 ApplicationComponent
     *
     * @return ApplicationComponent
     */
    protected AppCompontent getAppComponent() {
        return DaggerApplication.getAppComponent();
    }


    /**
     * 权限请求结果回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasAllGranted = true;
        StringBuilder permissionName = new StringBuilder();
        for (String s : permissions) {
            permissionName = permissionName.append(s + "\r\n");
        }
        switch (requestCode) {
            case mRequestCode: {
                for (int i = 0; i < grantResults.length; ++i) {
                    if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                        hasAllGranted = false;
                        //在用户已经拒绝授权的情况下，如果shouldShowRequestPermissionRationale返回false则
                        // 可以推断出用户选择了“不在提示”选项，在这种情况下需要引导用户至设置页手动授权
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
                            new AlertDialog.Builder(this).setTitle("PermissionTest")//设置对话框标题
                                    .setMessage("【用户选择了不再提示按钮，或者系统默认不在提示（如MIUI）。" +
                                            "引导用户到应用设置页去手动授权,注意提示用户具体需要哪些权限】" +
                                            "获取相关权限失败:" + permissionName +
                                            "将导致部分功能无法正常使用，需要到设置页面手动授权")//设置显示的内容
                                    .setPositiveButton("去授权", new DialogInterface.OnClickListener() {//添加确定按钮
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件

                                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                            Uri uri = Uri.fromParts("package", getApplicationContext().getPackageName(), null);
                                            intent.setData(uri);
                                            startActivity(intent);
                                            dialog.dismiss();
                                        }
                                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                                @Override
                                public void onClick(DialogInterface dialog, int which) {//响应事件

                                    dialog.dismiss();
                                }
                            }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                                @Override
                                public void onCancel(DialogInterface dialog) {
                                    mRequestPermissionCallBack.denied();
                                }
                            }).show();//在按键响应事件中显示此对话框
                        } else {
                            //用户拒绝权限请求，但未选中“不再提示”选项
                            mRequestPermissionCallBack.denied();
                        }
                        break;
                    }
                }
                if (hasAllGranted) {
                    mRequestPermissionCallBack.granted();
                }
            }
        }
    }

    /**
     * 发起权限请求
     *
     * @param context
     * @param permissions
     * @param callback
     */
    public void requestPermissions(final Context context, final String[] permissions,
                                   RequestPermissionCallBack callback) {
        this.mRequestPermissionCallBack = callback;
        StringBuilder permissionNames = new StringBuilder();
        for (String s : permissions) {
            permissionNames = permissionNames.append(s + "\r\n");
        }
        //如果所有权限都已授权，则直接返回授权成功,只要有一项未授权，则发起权限请求
        boolean isAllGranted = true;
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_DENIED) {
                isAllGranted = false;
                if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, permission)) {
                    new AlertDialog.Builder(this).setTitle("PermissionTest")//设置对话框标题
                            .setMessage("【用户曾经拒绝过你的请求，所以这次发起请求时解释一下】" +
                                    "您好，需要如下权限：" + permissionNames +
                                    " 请允许，否则将影响部分功能的正常使用。")//设置显示的内容
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                                @Override
                                public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件

                                    ActivityCompat.requestPermissions(((Activity) context), permissions, mRequestCode);
                                }
                            }).show();//在按键响应事件中显示此对话框
                } else {
                    ActivityCompat.requestPermissions(((Activity) context), permissions, mRequestCode);
                }
                break;
            }
        }
        if (isAllGranted) {
            mRequestPermissionCallBack.granted();
            return;
        }
    }

    public void umShare(final String title, final String content, final String url, final int imageId) {
        PermissionsUtils.requestPermissions2(this, new PermissionsUtils.OnDoCallback() {
            @Override
            public void onDo() {
                UMWeb web = new UMWeb(url);
                UMImage thumb = new UMImage(DaggerApplication.getIns(), imageId);
                web.setTitle(title);//标题
                web.setThumb(thumb);  //缩略图
                web.setDescription(content);//描述
                new ShareAction(IBaseStatusBarActivity.this)
                        .withMedia(web)
                        .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(shareListener)
                        .open();
            }

            @Override
            public void onUnDo() {

            }
        });
    }

    public void umShareNetImg(final String title, final String content, final String url, final String imageUrl) {
        PermissionsUtils.requestPermissions2(this, new PermissionsUtils.OnDoCallback() {
            @Override
            public void onDo() {
                UMWeb web = new UMWeb(url);
                UMImage thumb = new UMImage(DaggerApplication.getIns(), imageUrl);
                web.setTitle(title);//标题
                web.setThumb(thumb);  //缩略图
                web.setDescription(content);//描述
                new ShareAction(IBaseStatusBarActivity.this)
                        .withMedia(web)
                        .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(shareListener)
                        .open();
            }

            @Override
            public void onUnDo() {

            }
        });
    }


    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(IBaseStatusBarActivity.this, "成功了", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(IBaseStatusBarActivity.this, "失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(IBaseStatusBarActivity.this, "取消了", Toast.LENGTH_LONG).show();

        }
    };

    /**
     * 权限请求结果回调接口
     */
    public interface RequestPermissionCallBack {
        /**
         * 同意授权
         */
        void granted();

        /**
         * 取消授权
         */
        void denied();
    }

}
